const user = {

	// 调用登录接口，换取永久的 token
	async login(userInfo, fid) {
		let login_state = false
		// 调用微信登录接口
		const [err, res] = await uni.login().catch(err => err)
		// 判断是否 uni.login() 调用失败
		if (err || res.errMsg !== 'login:ok') {
			uni.$showError('登录失败！')
			login_state = false
		}

		console.log(res);

		await uni.$http.post("/account/login", {
			code: res.code
		}).then(({
			data: loginResult
		}) => {
			uni.$showMsg(loginResult.msg);
			if (loginResult.code !== uni.$code.successCode) {
				login_state = false
				throw new Error()
			}
			uni.$store.commit('user/updateToken', loginResult.data.baseInfo.uid)
			uni.$store.commit('user/updateUserInfo', {
				avatarUrl: userInfo.avatarUrl,
				nickName: userInfo.nickName,
				phone: ''
			})
		}).then(() => {
			this.getUserInfo()
			// 如果是点击别人的邀请且未登录，则发起申请加入的请求
			if (fid)
				uni.$api.fridge.join(fid)
			else uni.$api.fridge.getAll()
			login_state = true
		}).catch(() => {

		}).finally(() => {

		})
		return new Promise((resolve, reject) => {
			if (login_state)
				resolve("登录成功")
			else reject("登录失败")
		})
	},

	async getCellPhoneVerificationCode(phoneNum) {
		const {
			data: res
		} = await uni.$http.get("/account/getCellPhoneVerificationCode?phoneNum=" + phoneNum)
		if (res.code !== uni.$code.successCode) return uni.$showMsg(res.msg)
		uni.$showMsg('验证码已发出，请注意查收');
		return res.code
	},

	async getUserInfo() {
		const {
			data: res
		} = await uni.$http.get("/account/getUserInfo")
		if (res.code !== uni.$code.successCode) return uni.$showMsg(res.msg)
		uni.$store.commit('user/updateUserInfo', {
			avatarUrl: res.data.avatar,
			nickName: res.data.name,
			phone: res.data.phoneNumber || ''
		})
	},

	async getAvatarByPhone(phone) {
		const {
			data: res
		} = await uni.$http.post("/account/getUserAvatar", {
			phoneNumber: phone
		})
		if (res.code !== uni.$code.successCode) return uni.$showMsg(res.msg)
		return res.data.avatar
	},

	async updateUserInfo(formData) {
		const {
			data: res
		} = await uni.$http.put("/account/update", formData)
		if (res.code !== uni.$code.successCode) return uni.$showMsg(res.msg)
		uni.$store.commit('user/updateUserInfo', {
			avatarUrl: formData.avatarUrl,
			nickName: formData.nickName,
			phone: formData.phone || ''
		})
		uni.$showMsg('保存成功')
	}

}

export default user